package com.cz.nongyetongv5.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils.TruncateAt;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.adapter.TongXunLuListAdapter;
import com.cz.nongyetongv5.adapter.config.CommonConstants;
import com.cz.nongyetongv5.adapter.dao.DatabaseHelper;
import com.cz.nongyetongv5.application.InitApplication;
import com.cz.nongyetongv5.bean.LinkMan;
import com.cz.nongyetongv5.bean.Town;
import com.cz.nongyetongv5.bean.User;
import com.cz.nongyetongv5.custom.dialog.CustomDialog;
import com.cz.nongyetongv5.utils.CharsetUtil;
import com.cz.nongyetongv5.utils.GoHomeUtil;

import java.util.ArrayList;
import java.util.List;

public class TongXunLuActivity extends Activity implements OnItemClickListener,
		OnClickListener {

	/**
	 * 用户对象
	 */
	private User user = null;

	/**
	 * 数据库对象
	 */
	private DatabaseHelper db = null;

	/**
	 * 所有乡镇的数据集合
	 */
	private List datas = null;

	/**
	 * 通讯录适配器
	 */
	private TongXunLuListAdapter adpTongXunLu = null;

	/**
	 * ListView列表对象
	 */
	private ListView lvTongXunLu = null;

	/**
	 * 标记所有的省市级
	 */
	private List<Town> navgationDatas = new ArrayList<Town>();

	/**
	 * 类别筛选的布局
	 */
	private ViewGroup llCategoryLayout = null;

	private Button one = null;

	private Button tow = null;

	private Button three = null;

	// 当前的类别
	private int currentCategory = 3;

	/**
	 * 联系人的筛选
	 */
	private EditText edtFilterLinkMan = null;

	private ViewGroup navgationLayout = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		InitApplication initApplication = (InitApplication) getApplicationContext();

		initApplication.getActivities().add(this);

		setContentView(R.layout.tongxunlu);

		navgationLayout = (ViewGroup) findViewById(R.id.llNavgationLayout);

		llCategoryLayout = (ViewGroup) findViewById(R.id.llCategoryLayout);

		one = (Button) llCategoryLayout.getChildAt(0);
		one.setOnClickListener(this);

		tow = (Button) llCategoryLayout.getChildAt(2);
		tow.setOnClickListener(this);

		three = (Button) llCategoryLayout.getChildAt(4);
		three.setOnClickListener(this);

		if (getIntent() != null
				&& getIntent().getSerializableExtra("user") != null) {
			user = (User) getIntent().getSerializableExtra("user");
		}

		db = new DatabaseHelper(this, CommonConstants.DBNAME, null,
				CommonConstants.DATABASE_VERSION);

		// Town town = db.queryTownById(user.getCityId());
		//
		// navgationDatas.add(0, town);

		if (user.getKnowRegion() != null) {

			String code = user.getKnowRegion();

			while (true) {

				Town town = db.queryTownById(code);

				if (town.getCode() == user.getProvinceId()) {
					break;
				}

				navgationDatas.add(0, town);

				code = town.getParent_code();

				if (user.getTown_path_id().length() > 3 && "32".equals(code)) {

					break;
				}

				if (code == null) {
					break;
				}

			}

			notifyDatasetNavgation();

		}

		lvTongXunLu = (ListView) findViewById(R.id.lvTongXunLu);

		lvTongXunLu.setOnItemClickListener(this);

		ViewGroup btnBack = (ViewGroup) findViewById(R.id.btnBack);

		btnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				doBack();
			}
		});

		// 设置当前类别
		setCurrentCategory(currentCategory);

		notifyDatasetNavgation();

		initListView(getCurrentCategory());

		/**
		 * 联系人
		 */
		edtFilterLinkMan = (EditText) findViewById(R.id.edtFilterLinkMan);

		edtFilterLinkMan.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
									  int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
										  int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {

				String filter = s.toString().trim();

				if (CharsetUtil.isNotNull(filter)) {

					// 查询联系人

					List<LinkMan> linkMans = db.queryLinkManByFilter(
							user.getKnowRegion() + "", filter);

					if (linkMans.size() > 0) {
						adpTongXunLu = new TongXunLuListAdapter(
								TongXunLuActivity.this, linkMans, db,
								TongXunLuActivity.this);

						lvTongXunLu.setAdapter(adpTongXunLu);

						// 隐藏状态栏
						llCategoryLayout.setVisibility(View.GONE);

						navgationLayout.setVisibility(View.GONE);

					} else {
						Toast.makeText(TongXunLuActivity.this, "没有更多数据 ",
								Toast.LENGTH_SHORT).show();
					}

				} else {
					adpTongXunLu = new TongXunLuListAdapter(
							TongXunLuActivity.this, datas, db,
							TongXunLuActivity.this);

					lvTongXunLu.setAdapter(adpTongXunLu);

					llCategoryLayout.setVisibility(View.VISIBLE);

					navgationLayout.setVisibility(View.VISIBLE);
				}

			}

		});

		loadRightTitle();
	}

	/**
	 * 加载去主页的按钮
	 */
	public void loadRightTitle() {

		ViewGroup btnMeanMore = (ViewGroup) findViewById(R.id.btnMeanMore);

		View view = GoHomeUtil.createPopView(getApplicationContext(),
				new String[] { "主页" });

		// 弹出更多的菜单
		final PopupWindow pop = new PopupWindow(view,
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false);

		// 需要设置一下此参数，点击外边可消失
		pop.setBackgroundDrawable(new BitmapDrawable());

		// 设置点击窗口外边窗口消失
		pop.setOutsideTouchable(true);

		// 设置此参数获得焦点，否则无法点击
		pop.setFocusable(true);

		final Button btn01 = (Button) pop.getContentView().findViewWithTag(
				"btn0");

		OnClickListener menuOnClick = new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (v == btn01) {
					GoHomeUtil.goHome(getApplicationContext());
				}
			}
		};

		btn01.setOnClickListener(menuOnClick);

		btnMeanMore = (ViewGroup) findViewById(R.id.btnMeanMore);

		btnMeanMore.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (pop.isShowing()) {
					// 隐藏窗口，如果设置了点击窗口外小时即不需要此方式隐藏
					pop.dismiss();
				} else {
					// 显示窗口
					pop.showAsDropDown(v);
				}

			}
		});

	}

	/**
	 * 刷新导航数据
	 */
	private void notifyDatasetNavgation() {

		navgationLayout.removeAllViewsInLayout();

		for (int i = 0; i < navgationDatas.size(); i++) {

			TextView tvTextView = new TextView(this);
			tvTextView.setTextColor(getResources()
					.getColor(R.color.title_color));
			tvTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
			tvTextView.setTag(i);
			tvTextView.setBackgroundResource(R.drawable.btn_back_pressed);
			tvTextView.setClickable(true);

			int count = db.queryLinkManCountByTownId(navgationDatas.get(i)
					.getCode(), getCurrentCategory());

			tvTextView.setSingleLine(true);
			tvTextView.setEllipsize(TruncateAt.END);

			tvTextView.setText(navgationDatas.get(i).getName()
					+ "\u0020[\u0020" + count + "\u0020]\u0020>>");

			tvTextView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					int position = (Integer) v.getTag();

					for (int j = navgationDatas.size() - 1; j > position; j--) {
						navgationDatas.remove(j);
					}

					notifyDatasetNavgation();

					initListView(getCurrentCategory());

				}

			});

			//			if (Long.parseLong(navgationDatas.get(i).getCode()) >= Long
			//					.parseLong(user.getKnowRegion())) {

			tvTextView.setClickable(true);
			//			} else {
			//
			//				tvTextView.setClickable(false);
			//			}

			navgationLayout.addView(tvTextView, new LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		}

	}

	/**
	 * 根据当前的
	 */
	private void initListView(int category) {

		String currentTownId = "-1";

		currentTownId = getCurrentTown().getCode();

		List<Town> towns = db.queryTownByParent(currentTownId);

		List<LinkMan> linkMans = db.queryLinkManByTownId(currentTownId,
				category);

		if (towns.size() > 0) {
			this.datas = towns;
		}

		if (linkMans.size() > 0) {
			if (towns.size() == 0) {

				if (datas == null) {

					datas = new ArrayList();
				}

				datas.clear();
			}

			datas.addAll(0, linkMans);

		}

		if ((towns.size() + linkMans.size()) < 1) {
			if (datas != null) {
				datas.clear();
			}

		}

		adpTongXunLu = new TongXunLuListAdapter(TongXunLuActivity.this,
				linkMans, db, TongXunLuActivity.this);

		lvTongXunLu.setAdapter(adpTongXunLu);

		if ((towns.size() + linkMans.size()) < 1) {
			Toast.makeText(this, "没有更多数据 ", Toast.LENGTH_SHORT).show();

		} else {
			adpTongXunLu = new TongXunLuListAdapter(this, datas, db, this);

			lvTongXunLu.setAdapter(adpTongXunLu);
		}
	}

	@Override
	protected void onDestroy() {

		InitApplication initApplication = (InitApplication) getApplicationContext();

		initApplication.getActivities().remove(this);

		if (db != null) {
			db.close();
		}
		super.onDestroy();
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int position,
							long id) {

		Object data = adpTongXunLu.getItem(position);

		if (data != null && data instanceof LinkMan) {

			Intent to_detail = new Intent(this, LianXiRenDetail.class);

			LinkMan linkMan = (LinkMan) data;

			to_detail.putExtra("linkMan", linkMan);

			StringBuffer sbLocation = new StringBuffer();

			for (int i = 0; i < navgationDatas.size(); i++) {
				sbLocation.append(navgationDatas.get(i).getName());

				if (i < navgationDatas.size() - 1) {
					sbLocation.append(">>");
				}
			}

			if (sbLocation.length() > 0) {
				to_detail.putExtra("location", sbLocation.toString());

			}

			to_detail.putExtra("linkMan", linkMan);

			startActivity(to_detail);

		}

		if (data != null && data instanceof Town) {

			Town town = (Town) data;

			navgationDatas.add(town);

			notifyDatasetNavgation();

			initListView(currentCategory);
		}

	}

	@Override
	public void onBackPressed() {
		doBack();
	}

	private void doBack() {

		if (navgationDatas.size() < 2) {
			finish();
		} else {

			if (getCurrentTown().getCode().equals(user.getKnowRegion())) {

				finish();
			} else {

				navgationDatas.remove(navgationDatas.size() - 1);

				notifyDatasetNavgation();

				initListView(currentCategory);
			}
		}

	}

	@Override
	public void onClick(View v) {

		if (v == one) {
			currentCategory = 3;
			setCurrentCategory(currentCategory);

		}

		if (v == tow) {
			currentCategory = 2;
			setCurrentCategory(currentCategory);
		}

		if (v == three) {
			currentCategory = 1;
			setCurrentCategory(currentCategory);
		}

		if (v != null && v.getId() == R.id.llTongXuLuRightLayout) {

			int position = (Integer) v.getTag();

			Object object = adpTongXunLu.getItem(position);

			if (object != null && object instanceof LinkMan) {

				final LinkMan linkMan = (LinkMan) object;

				if (CharsetUtil.isNotNull(linkMan.getTel())
						&& CharsetUtil.isNotNull(linkMan.getMobile())) {

					// 弹出对话框
					final CustomDialog customDialog = new CustomDialog(
							TongXunLuActivity.this);

					customDialog
							.setOnActionClickListener(new OnClickListener() {
								@Override
								public void onClick(View v) {
									customDialog.dismiss();
								}
							});

					customDialog
							.setActionTxt(getString(R.string.jiandujiancha_item_cancle));
					customDialog
							.setTitle(getString(R.string.tongxunlu_btn_select_phone));

					ViewGroup view = (ViewGroup) getLayoutInflater().inflate(
							R.layout.tongxunlu_item_phone_select, null);

					// 个人电话
					final ViewGroup llPhone = (ViewGroup) view
							.findViewById(R.id.llPhone);

					TextView tvPhone = (TextView) llPhone
							.findViewById(R.id.tvTitle);

					tvPhone.setText(linkMan.getMobile());

					// 办公室电话
					final ViewGroup llHomeTel = (ViewGroup) view
							.findViewById(R.id.llHomeTel);

					TextView tvHomeTel = (TextView) llHomeTel
							.findViewById(R.id.tvHomeTel);

					tvHomeTel.setText(linkMan.getTel());

					customDialog.setView(view);
					customDialog.show();

					llPhone.setClickable(true);
					llHomeTel.setClickable(true);

					OnClickListener playPhoneClickListener = new OnClickListener() {

						@Override
						public void onClick(View v) {

							customDialog.dismiss();

							// 如果是办公室电话
							if (v == llHomeTel) {

								playPhone(linkMan.getTel());
							}

							// 如果是手机
							if (v == llPhone) {
								playPhone(linkMan.getMobile());
							}
						}
					};

					llPhone.setOnClickListener(playPhoneClickListener);
					llHomeTel.setOnClickListener(playPhoneClickListener);
				} else {

					String phone = "";

					if (CharsetUtil.isNotNull(linkMan.getTel())) {
						phone = linkMan.getTel();

					} else if (CharsetUtil.isNotNull(linkMan.getMobile())) {
						phone = linkMan.getMobile();
					}

					playPhone(phone);
				}

			}

		}

	}

	/**
	 * 进行拨打电话的操作
	 *
	 * @param phone
	 */
	private void playPhone(String phone) {

		Intent intent_to_call = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"
				+ phone));

		startActivity(intent_to_call);
	}

	/**
	 * 设置当前类别
	 */
	private void setCurrentCategory(int category) {

		one.setBackgroundResource(R.drawable.btn_back_pressed);
		tow.setBackgroundResource(R.drawable.btn_back_pressed);
		three.setBackgroundResource(R.drawable.btn_back_pressed);

		if (category == 3) {
			one.setBackgroundColor(getResources().getColor(R.color.title_color));
		}

		if (category == 2) {
			tow.setBackgroundColor(getResources().getColor(R.color.title_color));
		}

		if (category == 1) {
			three.setBackgroundColor(getResources().getColor(
					R.color.title_color));
		}

		notifyDatasetNavgation();

		initListView(getCurrentCategory());

	}

	public int getCurrentCategory() {
		return currentCategory;
	}

	/**
	 * 获得当前的城镇
	 *
	 * @return
	 */
	private Town getCurrentTown() {
		Town town = navgationDatas.get(navgationDatas.size() - 1);
		return town;
	}

}
